package com.shangyueshang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangyueshang.common.SysConstants;
import com.shangyueshang.mapper.SysDeptMapper;
import com.shangyueshang.model.SysDept;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.service.SysDeptService;
import com.shangyueshang.utils.SecurityUtil;
import org.apache.tomcat.jni.Local;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/5 18:42
 * @version: v1.0.0
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
	
	@Override
	public HttpResult saveUpdate(SysDept entity) {
		SysDept _dept = super.getById(entity.getId());
		if (_dept != null) {
			entity.setLastUpdateTime(LocalDateTime.now());
			entity.setLastUpdator(SecurityUtil.getUsername());
		} else {
			entity.setCreateTime(LocalDateTime.now());
			entity.setCreator(SecurityUtil.getUsername());
		}
		if ((_dept = this.findByName(entity.getName())) != null
				&& !_dept.getId().equals(entity.getId())) {
			return HttpResult.fail("该部门名称已存在");
		}
		return HttpResult.ok(super.saveOrUpdate(entity));
	}
	
	@Override
	public List<SysDept> findTree() {
		List<SysDept> treeDepts = new ArrayList<>();
		List<SysDept> sysDepts = super.list();
		for (SysDept dept : sysDepts) {
			if (dept.getParentId() == null || dept.getParentId() == 0) {
				dept.setLevel(0);
				treeDepts.add(dept);
			}
		}
		this.findChildren(treeDepts, sysDepts);
		return treeDepts;
	}
	
	private void findChildren(List<SysDept> treeDepts, List<SysDept> sysDepts) {
		for (SysDept treeDept : treeDepts) {
			List<SysDept> children = new ArrayList<>();
			for (SysDept dept : sysDepts) {
				if (treeDept.getId() != null && treeDept.getId().equals(dept.getParentId())) {
					dept.setParentName(treeDept.getParentName());
					dept.setLevel(treeDept.getLevel() + 1);
					children.add(dept);
				}
			}
			treeDept.setChildren(children);
			//递归处理
			this.findChildren(children, sysDepts);
		}
	}
	
	private SysDept findByName(String name) {
		QueryWrapper<SysDept> queryWrapper =
				new QueryWrapper<SysDept>()
						.eq(SysConstants.name, name);
		return super.getOne(queryWrapper);
	}
}
